package com.homework.boot_demo.service;

import com.homework.boot_demo.dao.Student;
import com.homework.boot_demo.dao.StudentRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collection;
import java.util.List;
@Service
public class StudentServiceImp implements StudentService{

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public Student getStudentById(int id) {
        return studentRepository.findById(id).orElseThrow(RuntimeException::new);
    }

    @Override
    public int addNewStudent(Student student) {
        List <Student>studentlist=studentRepository.findByEmail(student.getEmail());

        if(!CollectionUtils.isEmpty(studentlist)){
            throw new IllegalStateException("email:"+student.getEmail()+" already exist");
        }
        Student student1=studentRepository.save(student);
        return student1.getId();
    }

    @Override
    public void deleteStudentById(int id) {
        studentRepository.findById(id).orElseThrow(()->new IllegalStateException("id:"+id+"does not exist"));

        studentRepository.deleteById(id);
    }

    @Override
    @Transactional
    public Student updateStudentById(int id, String name, String email) {
        Student studentInDb=studentRepository.findById(id).orElseThrow(()->new IllegalStateException("id:"+id+"does not exist"));

        if(StringUtils.hasLength(name)&& studentInDb.getName().equals(name)){
            studentInDb.setName(name);
        }
        if(StringUtils.hasLength(email)&& studentInDb.getEmail().equals(email)){
            studentInDb.setEmail(email);
        }
        Student student=studentRepository.save(studentInDb);
        return student;
    }


}
